package logic

import (
	"context"
	"gorm.io/gorm"
	"shop-cart/cache"
	"shop-cart/models"

	"shop-cart/taobaorpc/internal/svc"
	"shop-cart/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUpdateLogic {
	return &ProductUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductUpdateLogic) ProductUpdate(in *taobaorpc.ProductUpdateRequest) (*taobaorpc.ProductUpdateResponse, error) {
	// todo: add your logic here and delete this line
	product := models.Product{
		Model: gorm.Model{ID: uint(in.ProductId)},
		Title: in.Title,
		Price: float64(in.Price),
	}
	err := product.UpdateProduct(models.DB)
	if err != nil {
		return nil, err
	}
	m := map[string]interface{}{
		"title": product.Title,
		"price": product.Price,
	}
	if err = cache.CartProductUpdate(in.UserId, in.ProductId, m); err != nil {
		return nil, err
	}
	return &taobaorpc.ProductUpdateResponse{
		ProductId: int64(product.ID),
	}, nil
}
